<?php
/**
 * Roles Model
 * @author 		TAMDV
 * @date		2008 07 22 (yyyy MM dd)
 * @package    	Joomus.JBS
 * @subpackage 	Components
 * @link 		http://localhost/jbschedule/administrator/index.php?option=com_jbschedule
 * @license		GNU/GPL
 */

// no direct access
//defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.model' );

/**
 * Roles Model
 *
 * @package    Joomla.JBS
 * @subpackage Components
 */
class JBSModelRoles extends JModel {
	/**
	 * EventTypes data array
	 *
	 * @var array
	 */
	public $_data = null;

	/**
	 * Events total
	 *
	 * @var integer
	 */
	public $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	public $_pagination = null;
	
	
	
	function __construct()
	{
		parent::__construct();

		global $mainframe, $option;

		$limit		= $mainframe->getUserStateFromRequest( $option.'limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
		
		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}
	
	/**
	 * Method to get event types item data
	 *
	 * @access public
	 * @return array
	 */
	function getDataList()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();		
			//echo $query;	
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}
		//print_r($this->_data);
		
		return $this->_data;
	}
	
	/**
	 * Total nr of eventtypes
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		// Lets load the total nr if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}
	
	/**
	 * Build the query
	 *
	 * @access private
	 * @return string
	 */
	function _buildQuery()
	{
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();
					$query = 'SELECT ' .
					'r.id,' .
					'r.name,' .
					'r.description,' .
					'Count(u.system_user_id) AS members ' .
					'FROM ' .
					'#__jbschedule_roles r ' .
					'Left Join #__jbschedule_users u ON r.id = u.tsb_role_id ' .					
					$where.
					' GROUP BY ' .
					' r.name,' .
					'r.description '
					. $orderby
					;
//		echo $query;
		return $query;
	}

	/**
	 * Method to get a pagination object for the groups
	 *
	 * @access public
	 * @return integer
	 */
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}
	
	/**
	 * Build the order clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildContentOrderBy()
	{
		global $mainframe, $option;
		$nameField  = 'name';
		
		$filter_order		= $mainframe->getUserStateFromRequest( $option.'.roles.filter_order', 'filter_order',$nameField, 'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'.roles.filter_order_Dir', 'filter_order_Dir', '', 'word' );

		
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.', r.'.$nameField;

		return $orderby;
	}
	
/**
	 * Build the where clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildContentWhere()
	{
		global $mainframe, $option;

		$search 			= $mainframe->getUserStateFromRequest( $option.'.search', 'search', '', 'string' );
		$search 			= $this->_db->getEscaped( trim(JString::strtolower( $search ) ) );

		$where = array();
		// title là filed trong db
		$where[] = ' LOWER(r.name) LIKE \'%'.$search.'%\' ';

		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );

		return $where;
	}
	
	

	/**
	 * Method to set the hello identifier
	 *
	 * @access	public
	 * @param	int Hello identifier
	 * @return	void
	 */
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}

	function &getAllData()
	{
		if (empty( $this->_data ))
		{
			$query = 'SELECT ' .
					'#__jbschedule_roles.id,' .
					'#__jbschedule_roles.name,' .
					'#__jbschedule_roles.description,' .
					'Count(#__jbschedule_users.system_user_id) AS members ' .
					'FROM ' .
					'#__jbschedule_roles ' .
					'Left Join #__jbschedule_users ON #__jbschedule_roles.id = #__jbschedule_users.tsb_role_id ' .
					'GROUP BY ' .
					'#__jbschedule_roles.name,' .
					'#__jbschedule_roles.description';

			$this->_data = $this->_getList( $query );
		}

		return $this->_data;
	}
 	/**
 	 * Method to get a Roles
	 * @return object with data
	 */
	function &getData()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__jbschedule_roles '.
					'  WHERE id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id 			= 0;
			$this->_data->name 			= null;
			$this->_data->description 	= null;
		}
		return $this->_data;
	}

	/**
 	 * Method to get all functions
	 * @return object with data
	 */
	function &getFunctions(){
		$query = 'SELECT * '.' FROM #__jbschedule_functions';
		/*for ($i=0, $n=count( $this->_data ); $i < $n; $i++)	{
			$row = $this->_data[$i];
			echo "ID :".$row->id."<br>";
		}*/

		return $this->_getList( $query );
	}

	/**
 	 * Method to get all functions By Role Id
	 * @return object with data
	 */
	function getFunctionsByRoleId($roleId){
		$query = 'SELECT * FROM #__jbschedule_roles_functions WHERE role_id='.$roleId;
		return $this->_getList( $query );
	}

	/**
 	 * Method to get all functions By Role Id
	 * @return object with data
	 */
	function getGroupFunctions(){
		$query = 'SELECT * FROM #__jbschedule_function_groups';
		return $this->_getList( $query );
	}

	/**
 	 * Method to get all functions By Role Id
	 * @return object with data
	 */
	function getFunctionsByGroupId($groupId){
		$query = 'SELECT * FROM #__jbschedule_functions WHERE group_id='.$groupId;
		return $this->_getList( $query );
	}

	/**
 	 * Method to get all user not in role
	 * @return object with data
	 */
	function getUserIsNotRole(){
		$query = 'SELECT #__users.id,#__users.username FROM #__users where #__users.id not in (select #__jbschedule_users.system_user_id FROM #__jbschedule_users)';
		return $this->_getList( $query );
	}

	/**
 	 * Method to get all user in role
	 * @return object with data
	 */
	function getUserIsRole($roleId){
		$query = 'SELECT *  FROM #__jbschedule_users Inner Join #__users ON #__jbschedule_users.system_user_id = #__users.id WHERE #__jbschedule_users.tsb_role_id = '.$roleId;
		return $this->_getList( $query );
	}
	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function store()
	{
		$row =& $this->getTable();

		$data 			= JRequest::get( 'post' );

		// Bind the form fields to the hello table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Make sure the record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Store the web link table to the database
		if (!$row->store()) {
			$this->setError( $row->getErrorMsg() );
			return false;
		}
		// delete before update or insert
		$query = 'SELECT function_id FROM #__jbschedule_roles_functions WHERE role_id = '.$row->id;
		$fiddb = $this->_getList( $query );
		if (count( $fiddb )){
			foreach($fiddb as $fid) {
				$this->_db->Execute( 'DELETE FROM #__jbschedule_roles_functions WHERE function_id='.$fid->function_id.' and role_id='.$row->id);
			}
		}

		//get all function id on form
		$fids 			= JRequest::getVar( 'fid', array(0), 'post', 'array' );
		if (count( $fids ))
		{
			foreach($fids as $fid) {
				$query = 'INSERT INTO #__jbschedule_roles_functions VALUES ('.$row->id.','.$fid.')';
				$this->_db->Execute( $query );
			}
		}

		//delete before update of table __jbschedule_users
		$queryRole = 'SELECT * FROM #__jbschedule_users WHERE tsb_role_id = '.$row->id;
		$tsbRoleId = $this->_getList( $queryRole );
		if (count( $tsbRoleId )){
			foreach($tsbRoleId as $trd) {
				$this->_db->Execute( 'DELETE FROM #__jbschedule_users WHERE system_user_id='.$trd->system_user_id.' and tsb_role_id='.$row->id);
				//echo 'DELETE FROM #__jbschedule_users WHERE system_user_id='.$trd->system_user_id.' and tsb_role_id='.$row->id.'<br>';
			}
		}
		// insert table users role
		$inRole = JRequest::getVar( 'tableOne', array(0), 'post', 'array' );
		//print_r($inRole);
		//echo "<br>";
		if (count( $inRole ))
		{
			if ($inRole[0] != 0){
				for ($i=0;$i<count($inRole);$i++){
					$query = 'INSERT INTO #__jbschedule_users VALUES ('.$inRole[$i].','.$row->id.')';
					//echo $query.'<br>';
					$this->_db->Execute( $query );
				}
			}
		}

		return true;
	}

	/**
	 * Method to delete record(s)
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function delete()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		$row =& $this->getTable();

		if (count( $cids ))
		{
			foreach($cids as $cid) {
				//Delete row jbschedule_roles_functions by role_id
				$query = 'SELECT function_id FROM #__jbschedule_roles_functions WHERE role_id = '.$cid;
				$fids = $this->_getList( $query );
				foreach($fids as $fid) {
					$this->_db->Execute( 'DELETE FROM #__jbschedule_roles_functions WHERE function_id='.$fid->function_id );
					//echo 'DELETE FROM #__jbschedule_roles_functions WHERE function_id='.$fid->function_id.'<br>';
				}

				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );
					return false;
				}
			}
		}
		return true;
	}
}

?>